<?php
namespace bgb\csv;
/**
 * csv导出
 * User: lys
 * Date: 18/05/2018
 * Time: 11:15
 */
class Csv
{

    /**
     * csv导出封装
     * @param array $outConfig  //对应数据列表 key=>value
     * @param  $filename //导出文件名
     * @param  $func //匿名函数返回数据
     * @param $page  //从第几个 $page_size 开始
     * @param $page_size  //每次导出多少条
     */
    public static function exportCsvEx($outConfig,$filename, $func, $page, $page_size){
        set_time_limit(0);
        $pageInfoFunc = function ($res, $page, $page_size) {
            $pageInfo = [
                'first_page' => 1,  //首页
                'total_page' => ceil($res['total'] / $page_size),  //总页数
                'total_count' => $res['total'], //总条数
                'current_page' => $page, //当前页
                'page_size' => $page_size, //显示条数
                'data' => $res['data']  //list数据
            ];
            if ($pageInfo['current_page'] < $pageInfo['total_page']) {
                $pageInfo['next_page'] = $pageInfo['current_page'] + 1;  //下一页
            } else {
                $pageInfo['next_page'] = null;
            }
            if ($pageInfo['current_page'] > $pageInfo['first_page']) {
                $pageInfo['prv_page'] = $pageInfo['current_page'] - 1;  //上一页
            } else {
                $pageInfo['prv_page'] = null;
            }
            return $pageInfo;
        };
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename . '.csv');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $fields = array_values($outConfig);
        $str = implode(',', array_keys($outConfig)) . "\r\n";
        ob_end_clean();
        ob_start();
        echo iconv('utf-8', 'gbk//IGNORE', $str);
        ob_flush();
        flush();
        ob_end_clean();
        do {
            ob_start();
            $str = '';
            $res = $func($page, $page_size);
            $pageInfo = $pageInfoFunc($res, $page, $page_size);
            foreach ($pageInfo['data'] as $val) {
                foreach ($fields as $field_name) {
                    if (strstr($val[$field_name], ',') || strstr($val[$field_name], '"')) {
                        $str .= iconv('utf-8', 'gbk//IGNORE', '"' . $val[$field_name]) . '"' . "\t" . ',';
                    } else {
                        $str .= iconv('utf-8', 'gbk//IGNORE', $val[$field_name]) . "\t" . ',';
                    }
                }
                $str = substr($str, 0, strlen($str) - 1);
                $str .= "\r\n";
            }
            echo $str;
            ob_flush();
            flush();
            ob_end_clean();
            $pageInfo['next_page'] != null && $page = $pageInfo['next_page'];
        } while ($pageInfo['next_page'] != null);
    }

}